package com.gaohe.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaohe.mapper.ShoppingCartMapper;
import com.gaohe.pojo.ShoppingCart;
import com.gaohe.pojo.User;
import com.gaohe.service.ShoppingCartService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImp extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Override
    @Transactional
    public void addShoppingCarts(ShoppingCart shoppingCart, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        shoppingCart.setUserId(user.getId());
        shoppingCart.setCreateTime(LocalDateTime.now());
        //根据dishId或者setMealId去查询是否存在购物信息
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        if (shoppingCart.getDishId() != null) {
            lqw.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        } else {
            lqw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart one = this.getOne(lqw);
        if (one != null) {
            one.setNumber(one.getNumber() + 1);
            this.updateById(one);
        } else {
            this.save(shoppingCart);
        }
    }

    @Override
    public void subShoppingCarts(ShoppingCart shoppingCart, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        shoppingCart.setUserId(user.getId());
        shoppingCart.setCreateTime(LocalDateTime.now());
        //根据dishId或者setMealId去查询是否存在购物信息
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        if (shoppingCart.getDishId() != null) {
            lqw.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        } else {
            lqw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart one = this.getOne(lqw);
        if (one.getNumber() > 1) {
            one.setNumber(one.getNumber() - 1);
            this.updateById(one);
        } else {
            this.removeById(one);
        }

    }
}
